<template>
  <div>
    姓名:
    <input v-model.trim="form.name" type="text" />
    <br />年龄:
    <input v-model.number="form.age" type="text" />
    <br />性别:
    <select v-model="form.gender">
      <option value="男">男</option>
      <option value="女">女</option>
    </select>
    <br />
    <button @click="add">添加</button>
    <button @click="put(form.id)">修改</button>
    <br />
    <table border>
      <thead>
        <tr>
          <th>序号</th>
          <th>姓名</th>
          <th>年龄</th>
          <th>性别</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item, index) in arr" :key="item.id">
          <td>{{ index + 1 }}</td>
          <td>{{ item.name }}</td>
          <td>{{ item.age }}</td>
          <td>{{ item.gender }}</td>
          <td>
            <button @click="del(item.id)">删除</button>&nbsp;
            <button @click="edit(item.id)">编辑</button>
          </td>
        </tr>
      </tbody>
    </table>
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: [
        { id: 11, name: "Tom", gender: "男", age: 19 },
        { id: 22, name: "Jone", gender: "女", age: 21 }
      ],
      form: {
        name: "",
        age: "",
        gender: "",
        id: ""
      }
    };
  },
  methods: {
    add() {
      const { name, age, gender } = this.form;
      if (name.length === 0 || age === "" || gender === "")
        return alert("输入数据");
      this.arr.push(this.form);
      this.form = {};
    },
    edit(id) {
      const obj = this.arr.find(item => item.id === id);
      // console.log(obj);
      this.form = { ...obj };
    },
    put(id) {
      // console.log(id);
      const index = this.arr.findIndex(item => item.id === id);
      // console.log(index);
      this.arr.splice(index, 1, this.form);
      this.form = {};
    },
    del(id) {
      const index = this.arr.findIndex(item => item.id === id);
      this.arr.splice(index, 1);
    }
  }
};
</script>

<style scoped>
table {
  /* border: 1px solid black; */
  border-collapse: collapse;
}
td,
th {
  padding: 10px;
}
</style>
